#include <QStyle>
#include <QMenu>
#include <QSlider>
#include <QLabel>
#include <QWidgetAction>
#include <QWebFrame>
#include <QWebView>
#include <QPrintDialog>
#include <QPrinter>
#include <QCompleter>
#include <QWebHistory>

#include "configurationmanager.h"
#include "browserwidget.h"
#include "webhistorycompleter.h"
#include "ui_browserwidget.h"

namespace Legenday{

BrowserWidget::BrowserWidget(QWidget *parent, ConfigurationManager *config) :
    QWidget(parent),
    m_configurationManager(config),
    ui(new Ui::BrowserWidget)
{
	ui->setupUi(this);
	setupToolbarMenu();
	setupMainToolbar();
	connect(ui->webView,SIGNAL(titleChanged(QString)),this,SLOT(on_titleChanged(QString)));

#if 1
	m_completer = new QCompleter(this);
	m_completer->setModel(new WebHistoryModel(m_completer,ui->webView->history()));
	m_completer->setCaseSensitivity(Qt::CaseInsensitive);
	m_completer->setCompletionMode(QCompleter::InlineCompletion);
#else
	QStringList sites;
	sites 	<< "http://www.google.com"
		<< "http://yahoo.com"
		<< "http://www.whatsup.co.il"
		<< "http://www.walla.co.il";
	m_completer = new QCompleter(sites,this);
#endif
	m_completer->setCaseSensitivity(Qt::CaseInsensitive);
//	m_completer->setCompletionMode(QCompleter::PopupCompletion);
//	m_completer->setCompletionMode(QCompleter::InlineCompletion);
	m_completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
	ui->lineAddress->setCompleter(m_completer);
}

BrowserWidget::~BrowserWidget()
{
	delete ui;
}

void	BrowserWidget::setConfigurationManager(ConfigurationManager *config)
{
	// TODO updated internal display, configuration etc
	m_configurationManager = config;
}

ConfigurationManager* BrowserWidget::getConfigurationManager()
{
	return m_configurationManager;
}

void	BrowserWidget::on_newCommand_triggered()
{
	m_configurationManager->openNewPage();
}

void	BrowserWidget::on_lineAddress_returnPressed()
{
	ui->webView->setUrl( QUrl::fromUserInput(ui->lineAddress->text()) );
	ui->webView->setFocus();
}

void	BrowserWidget::on_webView_loadStarted()
{
	ui->lineAddress->setEnabled(false);
	ui->stopReloadButton->setText(tr("Stop"));
	ui->stopReloadButton->setIcon(style()->standardIcon(QStyle::SP_BrowserStop));
}

void	BrowserWidget::on_webView_loadFinished(bool ok)
{
	ui->lineAddress->setEnabled(true);
	ui->stopReloadButton->setText(tr("Reload"));
	ui->stopReloadButton->setIcon(style()->standardIcon(QStyle::SP_BrowserReload));
	if (ok)
		ui->lineAddress->setText( ui->webView->url().toString() );
}

void	BrowserWidget::copy()
{
	ui->webView->page()->action(QWebPage::Copy)->trigger();
}

void	BrowserWidget::cut()
{
	ui->webView->page()->action(QWebPage::Cut)->trigger();
}

void	BrowserWidget::paste()
{
	ui->webView->page()->action(QWebPage::Paste)->trigger();
}

void	BrowserWidget::setUrl(QUrl url)
{
	ui->webView->setUrl(url);
}

void	BrowserWidget::saveWebPage()
{

}

void	BrowserWidget::find()
{

}

void	BrowserWidget::printWebPage()
{
	QPrinter printer;
	QPrintDialog *dialog = new QPrintDialog(&printer, this);
	dialog->setWindowTitle(tr("Print Document"));
	if (dialog->exec() != QDialog::Accepted)
		return;
	ui->webView->page()->mainFrame()->print(&printer);
}

/*
 void	BrowserWidget::showTools()
{

}
*/

void	BrowserWidget::showBookmarks()
{

}

void	BrowserWidget::showHistory()
{

}

void	BrowserWidget::showDownloads()
{

}

void	BrowserWidget::showOptions()
{
	if (m_configurationManager==NULL)
		return;
	m_configurationManager->showConfigurationDialog();
}

void	BrowserWidget::selectUrlBar()
{
	ui->lineAddress->selectAll();
	ui->lineAddress->setFocus(Qt::ShortcutFocusReason);
}

void	BrowserWidget::editActionsClicked(QString linkURL)
{
	if (m_configurationMenu->isVisible())
		m_configurationMenu->hide();
	if (linkURL == ":copy")
		copy();
	else if (linkURL == ":cut")
		cut();
	else if (linkURL == ":paste")
		paste();
}

void	BrowserWidget::on_titleChanged(QString s)
{
	emit(titleChanged(s));

	QWidget    *w   = qobject_cast<QWidget*>(parent());
	QTabWidget *tab = qobject_cast<QTabWidget*>(parent()->parent());

/*	WebHistoryModel *model = qobject_cast<WebHistoryModel*>(ui->lineAddress->completer()->model());
	if (model)
		model->refetchHistory();*/
	ui->lineAddress->setCompleter(m_completer);

	if (tab != NULL)
	{
		int i = tab->indexOf(this);
		if (i>=0)
			tab->setTabText(i, s);
	}

	if (w != NULL)
	{
		w->setWindowTitle(s);
	}

}

void	BrowserWidget::setupToolbarMenu()
{
	m_configurationMenu = new QMenu;
	QWidgetAction *zoomWidgetAction = new QWidgetAction(m_configurationMenu);
	QWidget *zoomOperationWidget = new QWidget;
	QBoxLayout *bl1 = new QBoxLayout(QBoxLayout::LeftToRight);

	bl1->addSpacing(12);
	bl1->addWidget( new QLabel("Zoom") );
	bl1->addSpacing(10);
	QSlider *zoomSlider = new QSlider;
	zoomSlider->setMinimum(0);
	zoomSlider->setMaximum(100);
	zoomSlider->setOrientation(Qt::Horizontal);
	bl1->addWidget(zoomSlider);
	zoomOperationWidget->setLayout(bl1);
	zoomWidgetAction->setDefaultWidget(zoomOperationWidget);

	QWidgetAction *editWidgetActon = new QWidgetAction(m_configurationMenu);
	QWidget *editOperationsWidget = new QWidget;
	QBoxLayout *bl2 = new QBoxLayout(QBoxLayout::LeftToRight);
	bl2->addSpacing(12);

	QLabel *l;
	bl2->addWidget(new QLabel("Edit") );
	bl2->addSpacing(10);

	l =  new QLabel(
		QString("<a href=':cut'>%1</a> &nbsp; <a href=':copy'>%2</a> &nbsp; <a href=':paste'>%3</a>")
		.arg(tr("Cut")).arg(tr("Copy")).arg(tr("Paste"))
	);
	connect(l,SIGNAL(linkActivated(QString)),this,SLOT(editActionsClicked(QString)));
	bl2->addWidget(l);
	editOperationsWidget->setLayout(bl2);
	editWidgetActon->setDefaultWidget(editOperationsWidget);

	m_configurationMenu->addAction( tr("&New tab"), this, SLOT(on_newCommand_triggered()), QKeySequence::fromString("Ctrl+T") );
	m_configurationMenu->addSeparator();
	m_configurationMenu->addAction( editWidgetActon );
	m_configurationMenu->addSeparator();
	m_configurationMenu->addAction( zoomWidgetAction );
	m_configurationMenu->addSeparator();
	m_configurationMenu->addAction( tr("&Save page as"), this, SLOT(saveWebPage()), QKeySequence::SaveAs );
	m_configurationMenu->addAction( tr("&Find"), this, SLOT(find()), QKeySequence::SaveAs );
	m_configurationMenu->addAction( tr("&Print"), this, SLOT(printWebPage()), QKeySequence::SaveAs );
	m_configurationMenu->addAction( tr("&Tools"), this, SLOT(on_toolsCommand_triggered()), QKeySequence::SaveAs );
	m_configurationMenu->addSeparator();
	m_configurationMenu->addAction( tr("&Bookmark Manager"), this, SLOT(showBookmarks()), QKeySequence::SaveAs );
	m_configurationMenu->addAction( tr("&History"), this, SLOT(showHistory()), QKeySequence::SaveAs );
	m_configurationMenu->addAction( tr("&Downloads"), this, SLOT(showDownloads()), QKeySequence::SaveAs );
	m_configurationMenu->addSeparator();
	m_configurationMenu->addAction( tr("&Configuration"), this, SLOT(showOptions()), QKeySequence::SaveAs );

	QAction *a = NULL;
	a = new QAction(this);
	a->setShortcut( QKeySequence("Ctrl+L") );
	connect(a,SIGNAL(triggered()),this,SLOT(selectUrlBar()));
	addAction(a);

	/*a = new QAction(this);
	a->setShortcut( QKeySequence("Backspace") );
	connect(a,SIGNAL(triggered()), ui->webView->page()->action(QWebPage::Back) ,SLOT(activate));
	addAction(a); */
}

void	BrowserWidget::setupMainToolbar()
{
	if (ui==NULL)
		return;

	ui->backButton->setDefaultAction(ui->webView->page()->action(QWebPage::Back));
	ui->backButton->setIcon( style()->standardIcon(QStyle::SP_ArrowBack) );
	ui->backButton->setToolButtonStyle(Qt::ToolButtonFollowStyle);
	ui->backButton->setShortcut(QKeySequence::Back);

	ui->forwardButton->setDefaultAction(ui->webView->page()->action(QWebPage::Forward));
	ui->forwardButton->setIcon( style()->standardIcon(QStyle::SP_ArrowForward));
	ui->forwardButton->setToolButtonStyle( Qt::ToolButtonFollowStyle );
	ui->forwardButton->setShortcut(QKeySequence::Forward);

	ui->stopReloadButton->setDefaultAction(ui->webView->page()->action(QWebPage::Stop));
	ui->stopReloadButton->setIcon( style()->standardIcon(QStyle::SP_BrowserReload));
	ui->stopReloadButton->setToolButtonStyle( Qt::ToolButtonFollowStyle );

	ui->configButton->setIcon( style()->standardIcon(QStyle::SP_DialogResetButton) );
	ui->configButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui->configButton->setPopupMode(QToolButton::InstantPopup);
	ui->configButton->setMenu(m_configurationMenu);
}

} // Legebdady namespace

